<?php
/**
 * Created by PhpStorm.
 * User: cc
 * Date: 2024/8/12
 * Time: 15:34
 */

namespace app\astrologer\controller\v7;

use app\astrologer\controller\AstrAuth;
use app\common\cachemodel\zl8\Zl8AstrChatBusyDateRecord;
use app\common\cachemodel\zl8\Zl8AstrChatBusyRecord;
use app\common\cachemodel\zl8\Zl8UserChatReservationRecord;
use app\zyhsapi\model\ZyhsConsultChatRecord;
use app\zyhsapi\model\ZyhsConsultChatRecordAstr;
use app\zyhsapi\model\ZyhsConsultChatRecordDetails;
use think\response\Json;

class Consult extends AstrAuth
{
    private $appType2 = 2;

    public function getNewMessageCount()
    {
        $zyhsConsultChatRecordAstrModel = new ZyhsConsultChatRecordAstr();
        do
        {
            $newMsg = $zyhsConsultChatRecordAstrModel->getAstrUnreadAllNum($this->astrInfo['id'], 3) ? 1 : 0;
            if ($newMsg === 1)
            {
                break;
            }
            $newMsg = $zyhsConsultChatRecordAstrModel->getAstrUnreadAllNum($this->astrInfo['id'], 2) ? 1 : 0;
            if ($newMsg === 1)
            {
                break;
            }
            $pageData = $zyhsConsultChatRecordAstrModel->pageDataIds($this->astrInfo['id'], 1, 1, 100);

            $newMsg = $zyhsConsultChatRecordAstrModel->getAstrUnreadAllNum($this->astrInfo['id'], 1, $pageData['data']) ? 1 : 0;

        } while (false);

        return show(config('code.success'), '请求成功', ['is_new' => $newMsg]);
    }


    /**
     * 全部预约
     * @return Json
     * @throws \app\common\lib\exception\ApiException
     */
    public function reservationList()
    {
        $page = input('page/d', 1);
        $zl8UserChatReservationRecordModel = new Zl8UserChatReservationRecord();
        $reservationTimeListConfig = $zl8UserChatReservationRecordModel->reservationTimeList;
        $reservationTimeList = [
            'total' => 0,
            'per_page' => 1,
            'current_page' => 1,
            'last_page' => 1,
            'data' => [],
        ];
        // 获取指定咨询师的预约记录
        $astrReservationList = $zl8UserChatReservationRecordModel->getAstrReservationList($this->astrInfo['id']);
        if ($astrReservationList)
        {
            $ids = array_keys($astrReservationList);
            rsort($ids);
            // 统计有多少订单
            $total = count($ids);
            //获取数据分页信息
            $per_page = 20;// 当前订单订单每页显示数量
            $data_list = getPaginatorData($total, $page, $per_page);
            //获取分页后的数据
            $ids = array_slice($ids, $data_list['start'], $per_page);
            unset($data_list['start']);
            unset($data_list['end']);

            $astrReservationInfo = $zl8UserChatReservationRecordModel->batchGetInfoByIds($ids);
            // 批量获取所有用户的昵称和头像
            $allUserIds = array_unique(array_column($astrReservationInfo, 'uid'));
            $allUserInfo = (new \app\common\model\User())->batchGetUserInfo($allUserIds);
            foreach ($astrReservationInfo as $item)
            {
                //1=>咨询师待接受 2=>用户待履约 3=>用户已履约  4=>用户已取消 5=>用户未履约  6=>咨询师已拒绝  7=>咨询师未处理预约  8=>咨询师取消
                switch ($item['status'])
                {
                    case 1:
                        $item['status_dsc'] = '预约中';
                        break;
                    case 2:
                        $item['status_dsc'] = '预约成功';
                        break;
                    case 3:
                        $item['status_dsc'] = '已兑现';
                        break;
                    case 4:
                        $item['status_dsc'] = '已过期';
                        break;
                    case 7:
                    case 5:
                        $item['status_dsc'] = '已过期';
                        $item['status'] = 4;
                        break;
                    case 8:
                    case 6:
                        $item['status_dsc'] = '已拒绝';
                        $item['status'] = 5;
                        break;
                    default:
                        $item['status_dsc'] = '未知';
                }
                $reservationTimeList['data'][] = [
                    'id' => $item['id'],
                    'avatar' => $allUserInfo[$item['uid']]['avatar'],
                    'nickname' => $allUserInfo[$item['uid']]['nickname'],
                    'desc' => '预约时间：' . date('n月j日', strtotime($item['date'])) . ' ' . $reservationTimeListConfig[$item['h_id']],
                    'status' => $item['status'],//预约状态 1=>预约中【待接受】 2=>预约成功【待履约】3=>已兑现 4=>已过期 5=>已拒绝
                    'status_desc' => $item['status_dsc'],
                    'uid' => $item['uid'],
                ];
            }
        }
        return show(config('code.success'), '', $reservationTimeList);
    }

    /**
     * 指定日期预约列表
     * @return Json
     * @throws \Exception
     */
    public function dateReservationList()
    {
        $type = input('type/d', 1);
        if (!in_array($type, [1, 2, 3], true))
        {
            return show(config('code.error'), '请求异常');
        }

        $zl8UserChatReservationRecordModel = new Zl8UserChatReservationRecord();
        $reservationTimeListConfig = $zl8UserChatReservationRecordModel->reservationTimeList;
        $dateInfo = $this->generateDateInfo($type - 1);

        $reservationTimeList = [];
        $reservationIds = [];
        // 获取指定咨询师的预约记录
        $astrReservationList = $zl8UserChatReservationRecordModel->getAstrReservationList($this->astrInfo['id']);
        if ($astrReservationList)
        {
            $ids = array_keys($astrReservationList);
            $astrReservationInfo = $zl8UserChatReservationRecordModel->batchGetInfoByIds($ids);

            // 批量获取所有用户的昵称和头像
            $allUserIds = array_unique(array_column($astrReservationInfo, 'uid'));
            $allUserInfo = (new \app\common\model\User())->batchGetUserInfo($allUserIds);

            // 状态码描述统一管理
            $statusDescriptions = [
                1 => '预约中',
                2 => '预约成功',
                3 => '已兑现',
                4 => '已过期',
                5 => '已拒绝',
                6 => '已拒绝',
                7 => '已过期',
                8 => '已拒绝',
            ];
            foreach ($astrReservationInfo as $item)
            {
                if ($item['date'] === (int)$dateInfo['date'] && in_array($item['status'], [
                        $zl8UserChatReservationRecordModel->statusList['waiting_response'],
                        $zl8UserChatReservationRecordModel->statusList['wait_keep_promise'],
                    ], true))
                {
                    $statusDesc = $statusDescriptions[$item['status']] ?? '未知';

                    // 避免数组键名重复赋值
                    $reservationTimeList[] = [
                        'id' => $item['id'],
                        'avatar' => $allUserInfo[$item['uid']]['avatar'],
                        'nickname' => $allUserInfo[$item['uid']]['nickname'],
                        'desc' => '预约时间：' . date('n月j日', strtotime($item['date'])) . ' ' . $reservationTimeListConfig[$item['h_id']],
                        'status' => $item['status'], // 预约状态
                        'status_desc' => $statusDesc,
                        'uid' => $item['uid'],
                    ];
                    $reservationIds[] = $item['h_id'];
                }
            }
        }
        //获取咨询师休息记录
        $astrRestList = (new Zl8AstrChatBusyRecord())->getAstrChatBusyList($this->astrInfo['id']);
        $astrDateRestList = (new Zl8AstrChatBusyDateRecord())->getAstrDateBusyList($this->astrInfo['id']);
        $typeDate = in_array($dateInfo['date'], $astrDateRestList, false) ? 3 : null;
        $timeDate = [];
        foreach ($reservationTimeListConfig as $id => $value)
        {
            $typeTmp = 3;
            if ($astrRestList && !in_array($id, $astrRestList, false))
            {
                $typeTmp = 1;
            }
            if (in_array($id, $reservationIds, false))
            {
                $typeTmp = 2;
            }
            $timeDate[] = [
                'time_desc' => $value,
                'type' => $typeDate ?? $typeTmp,
            ];
        }
        if ($reservationTimeList)
        {
            array_multisort(array_column($reservationTimeList, 'id'), SORT_NUMERIC, SORT_DESC, $reservationTimeList);
        }
        $data = [
            'tab_name' => $dateInfo['name'],
            'date' => $dateInfo['date2'],
            'timeDate' => $timeDate,
            'sub_data' => $reservationTimeList,
        ];
        return show(config('code.success'), '', $data);
    }

    /**
     * 获取日期信息
     * @param $daysOffset
     * @return array
     */
    private function generateDateInfo($daysOffset)
    {
        return [
            'date' => date('Ymd', strtotime("+$daysOffset day")),
            'date2' => date('Y-m-d', strtotime("+$daysOffset day")),
            'name' => $daysOffset === 0 ? '今天' : ($daysOffset === 1 ? '明天' : '后天'),
        ];
    }

    /**
     * 处理预约
     * @return Json
     * @throws \Exception
     */
    public function handleReservation()
    {
        $id = input('id/d', 0);
        $status = input('status/d', 0);//1=>接受 2=>拒绝 3=>取消
        if (!in_array($status, [1, 2, 3], true))
        {
            return show(config('code.error'), '请求异常');
        }
        $zl8UserChatReservationRecordModel = new Zl8UserChatReservationRecord();
        $info = $zl8UserChatReservationRecordModel->getInfoById($id);
        if (!$info || $info['astr_id'] != $this->astrInfo['id'])
        {
            return show(config('code.error'), '请求异常');
        }
        if (!in_array($info['status'], [
            $zl8UserChatReservationRecordModel->statusList['waiting_response'],
            $zl8UserChatReservationRecordModel->statusList['wait_keep_promise'],
        ], true))
        {
            return show(config('code.error'), '请求异常');
        }
        // 状态码描述统一管理
        $statusDescriptions = [
            1 => [
                'status' => $zl8UserChatReservationRecordModel->statusList['wait_keep_promise'],
                'title' => '预约成功',
                'content' => '已接收预约，不见不散',
            ],
            2 => [
                'status' => $zl8UserChatReservationRecordModel->statusList['astr_refuse'],
                'title' => '预约拒绝',
                'content' => '非常抱歉，暂不方便',
            ],
            3 => [
                'status' => $zl8UserChatReservationRecordModel->statusList['astr_cancel'],
                'title' => '预约已取消',
                'content' => '因紧急情况，我取消了您的预约；非常遗憾也非常抱歉，您可以更改预约时间。',
            ],
        ];
        $res = $zl8UserChatReservationRecordModel->updateData($id, [
            'status' => $statusDescriptions[$status]['status'],
            'update_time' => $this->request->time(),
        ]);
        if ($res)
        {
            $consultChatRecordDetailsModel = new ZyhsConsultChatRecordDetails();
            if ($status === 3)
            {
                //插入会话
                $consultChatIdModel = new ZyhsConsultChatRecord();
                $chatId = $consultChatIdModel->getChatIdByAstrId($this->appType2, $info['uid'], $this->astrInfo['id']);
                if ($chatId)
                {
                    $reservationTimeListConfig = $zl8UserChatReservationRecordModel->reservationTimeList;
                    $timeDes = date('Y年n月j日', strtotime($info['date'] . ' 00:00')) . ' ' . $reservationTimeListConfig[$info['h_id']];
                    $chatDetail = [
                        'chat_id' => $chatId,
                        'app_type' => $this->appType2,
                        'uid' => $info['uid'],
                        'astr_id' => $this->astrInfo['id'],
                        'type' => 1,    //  1=>APP消息 2=>用户发送消息
                        'title' => '',
                        'content' => $timeDes, // 提问问题
                        'data_type' => 9,   // 9=>预约消息
                        'pid' => 0, // 待更新
                        'extend' => [
                            'reservation_info' => [
                                'title' => $statusDescriptions[$status]['title'],
                                'content' => $statusDescriptions[$status]['content'],
                                'time_des' => $timeDes,
                                'status' => $statusDescriptions[$status]['status'],
                            ],
                        ],
                        'create_time' => $this->request->time(),
                    ];
                    $chatDetail['id'] = $consultChatRecordDetailsModel->SaveData($chatId, $chatDetail)['id'];
                }
            } else
            {
                $chatDetail = $consultChatRecordDetailsModel->getInfoById($info['char_id']);
                $chatDetail['extend']['reservation_info']['status'] = $statusDescriptions[$status]['status'];
                $chatDetail['extend']['reservation_info']['title'] = $statusDescriptions[$status]['title'];
                $chatDetail['extend']['reservation_info']['content'] = $statusDescriptions[$status]['content'];
                $consultChatRecordDetailsModel->UpdateData($chatDetail['id'], ['extend' => $chatDetail['extend']]);
            }
            if (isset($chatDetail))
            {
                $userInfo = (new \app\common\model\User())->getUserinfo(['id' => $info['uid']]);
                $resData = $consultChatRecordDetailsModel->astrDataListResert([$chatDetail], $this->astrInfo, $userInfo, $this->appType2);
                $resData = current($resData);
            }
            return show(config('code.success'), 'success', $resData ?? []);
        }
        return show(config('code.error'), '服务异常，请稍后再试～');
    }

    /**
     * 获取预约配置
     * @return Json
     * @throws \Exception
     */
    public function getReservationConfig()
    {
        $zl8UserChatReservationRecordModel = new Zl8UserChatReservationRecord();
        $reservationTimeListConfig = $zl8UserChatReservationRecordModel->reservationTimeList;
        //获取咨询师休息记录
        $astrRestList = (new Zl8AstrChatBusyRecord())->getAstrChatBusyList($this->astrInfo['id']);
        $astrDateRestList = (new Zl8AstrChatBusyDateRecord())->getAstrDateBusyList($this->astrInfo['id']);
        $dates = [];
        $nowDate = date('Ymd');
        foreach ($astrDateRestList as $item)
        {
            if ($nowDate <= $item)
            {
                // 使用 substr 函数分割日期
                $year = substr($item, 0, 4);
                $month = substr($item, 4, 2);
                $day = substr($item, 6, 2);

                // 将各个部分组合成新的日期格式
                $dates[] = $year . '-' . $month . '-' . $day;
            }
        }
        $reservationTimeList = [];
        foreach ($reservationTimeListConfig as $id => $value)
        {
            $status = 3;
            if ($astrRestList && !in_array($id, $astrRestList, false))
            {
                $status = 1;
            }
            $reservationTimeList[] = [
                'id' => $id,
                'time_desc' => $value,
                'type' => $status,
            ];
        }
        return show(config('code.success'), '', ['data' => $reservationTimeList, 'dates' => $dates ? array_values($dates) : []]);
    }

    /**
     * 设置预约配置
     * @return Json
     * @throws \Exception
     */
    public function setReservationConfig()
    {
        $ids = input('ids/s', '');
        $dates = input('dates/s', '');
        $dates = json_decode($dates, true);

        $zl8AstrChatBusyRecordModel = new Zl8AstrChatBusyRecord();
        if ($ids)
        {
            $ids = explode(',', $ids);
            $ids = array_unique($ids);
            $ids = implode(',', $ids);
            if (strlen($ids) > 62)
            {
                return show(config('code.error'), '请求异常');
            }
            $astrDateRestList = $zl8AstrChatBusyRecordModel->getAstrChatBusyList($this->astrInfo['id']);
            if ($astrDateRestList)
            {
                $zl8AstrChatBusyRecordModel->updateData($this->astrInfo['id'], ['h_ids' => $ids]);
            } else
            {
                $zl8AstrChatBusyRecordModel->saveData(['astr_id' => $this->astrInfo['id'], 'h_ids' => $ids]);
            }
        } else
        {
            $astrDateRestList = $zl8AstrChatBusyRecordModel->getAstrChatBusyList($this->astrInfo['id']);
            if ($astrDateRestList)
            {
                $zl8AstrChatBusyRecordModel->updateData($this->astrInfo['id'], ['h_ids' => '']);
            }
        }

        $zl8AstrChatBusyDateRecordModel = new Zl8AstrChatBusyDateRecord();
        if ($dates)
        {
            $dates = array_unique($dates);
            $data = [];
            $dates = array_map('convertDateFormatToInt', $dates);
            foreach ($dates as $date)
            {
                $data[] = [
                    'astr_id' => $this->astrInfo['id'],
                    'date' => $date,
                    'create_time' => $this->request->time(),
                ];
            }
            $astrDateRestList = $zl8AstrChatBusyDateRecordModel->getAstrDateBusyList($this->astrInfo['id']);
            if ($astrDateRestList)
            {
                $zl8AstrChatBusyDateRecordModel->delData($this->astrInfo['id']);
            }
            ($zl8AstrChatBusyDateRecordModel)->saveData($data);
        } else
        {
            $astrDateRestList = $zl8AstrChatBusyDateRecordModel->getAstrDateBusyList($this->astrInfo['id']);
            if ($astrDateRestList)
            {
                $zl8AstrChatBusyDateRecordModel->delData($this->astrInfo['id']);
            }
        }
        return show(config('code.success'), 'success');
    }
}
